package com.ai5suoai.ams.web.ctrl.v1;

import com.ai5suoai.ams.service.UserService;
import com.ai5suoai.ams.web.util.MessageSourceUtil;
import com.ai5suoai.ams.web.util.ResponseEntityUtil;
import com.ai5suoai.ams.web.vo.UserVo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.Optional;

import javax.validation.Valid;

/**
 * 用户的 controller
 *
 * @author chenzhenjia
 * @since 2016/3/17
 */
@RestController
@RequestMapping(value = "api/v1/users/")
public class UserCtrl {
    @Autowired
    UserService userService;
    @Autowired
    ResponseEntityUtil responseEntityUtil;
    @Autowired
    MessageSourceUtil messageSourceUtil;

    /**
     * 用户注册,会判断用户的邮箱是否注册,用户名是否注册
     *
     * @param user 用户对象的vo
     */
    @RequestMapping(value = "register", method = RequestMethod.POST)
    public ResponseEntity register(@Valid UserVo user) {
        return userService.findOneByUsername(user.getUsername())
                .map(user1 -> responseEntityUtil.badRequest(messageSourceUtil.getMessage("username.used")))
                .orElseGet(() -> userService.findOneByEmail(user.getEmail())
                        .map(user1 -> responseEntityUtil.badRequest(messageSourceUtil.getMessage("email.used")))
                        //保存
                        .orElseGet(() -> Optional.ofNullable(userService.save(user))
                                // 保存成功
                                .map(u -> new ResponseEntity(HttpStatus.CREATED))
                                //保存失败
                                .orElseGet(() -> responseEntityUtil.serverError()))
                );
    }

    @RequestMapping(value = "activity", method = RequestMethod.PUT)
    public ResponseEntity activityUser() {
//userService.
        return null;
    }
}
